import BasicLayout from '@/layouts/BasicLayout.vue'
import FullLayout from '@/layouts/RouteView.vue'
import i18n from '@/locales'
import tool from '@/utils/tool'

const modules = import.meta.glob(
    [
        // '@/layouts/*.vue',   // 匹配某个文件夹下的所有 .vue 文件，布局文件没生效
        '@/layouts/**/*.vue',   // 匹配某个文件夹及其子文件夹下的所有 .vue 文件
        '@/views/**/*.vue'      // 匹配某个文件夹及其子文件夹下的所有 .vue 文件
    ], {
        eager: false // true是硬加载, false是懒加载
    }
)

// 前端路由表 (基于动态)
const constantRouterComponents = {
    // 基础页面 layout 必须引入
    BasicLayout: BasicLayout,
    FullLayout: FullLayout,
    '403': () => import(/* webpackChunkName: "error" */ '@/views/exception/403.vue'),
    '404': () => import(/* webpackChunkName: "error" */ '@/views/exception/404.vue'),
    'empty': () => import(/* webpackChunkName: "error" */ '@/views/exception/empty.vue'),
}

// 过滤树
export function treeFilter(tree, func) {
    return tree.map(node => ({ ...node })).filter(node => {
        node.children = node.children && treeFilter(node.children, func)
        return func(node) || (node.children && node.children.length)
    })
}

// 转换树数据
export function convertRoutes (routerMap) {
    const accessedRouters = []
    routerMap.forEach(item => {
        item.meta = item.meta ? item.meta : {}
        if(item.title && !item.meta.title) {
            item.meta.title = item.title
        }
        //处理外部链接特殊路由
        if (item.meta.type === 'iframe') {
            item.meta.url = item.path
            item.path = `/i/${ item.name }`
        }
        // 是否隐藏面包屑
        item.meta.hiddenBreadcrumb = item.meta.hiddenBreadcrumb?item.meta.hiddenBreadcrumb:false
        // 是否显示菜单
        item.meta.showMenu = item.meta.showMenu !== undefined ? item.meta.showMenu : true
        // if(item.component === 'BasicLayout') {
        //     console.log(modules)
        //     console.log(constantRouterComponents[item.component])
        // }
        // console.log(item)
        //MAP转路由对象
        let route = {
            path: item.path,
            name: item.name,
            title: item.title,
            meta: item.meta,
            redirect: item.redirect ? item.redirect : null,
            children: item.children ? convertRoutes(item.children) : null,
            component: item.component ? loadComponent(item.component) : null
            // component: item.component
        }
        accessedRouters.push(route)
    })

    // console.log(accessedRouters);
    return accessedRouters
}

// 加载页面
export function loadComponent (component) {
    if (component) {
        // console.log(component)
        // console.log(`/src/${component}.vue`)
        // console.log(modules);
        return modules[`/src/${component}.vue`]
    } else {
        return () => import('@/views/exception/empty.vue')
    }
}

// 处理路由里的每一个title的语言包
export function processLanguage (routes) {
    for (let i = 0, len = routes.length; i < len; i++) {
        const item = routes[i]
        if(item.title) {
            item.title = i18n.global.t(item.title)
        }
        if (item.children && item.children.length > 0) {
            processLanguage(item.children) // 递归遍历 children
        }
    }
    return routes
}

// 路由扁平化
export function flatAsyncRoutes (routes, breadcrumb = []) {
    for (let i = 0, len = routes.length; i < len; i++) {
        const item = routes[i]
        if(!item.meta.hiddenBreadcrumb) {
            item.meta.breadcrumb = [...breadcrumb, item] // 添加 breadcrumb 字段
        }
        if (item.children && item.children.length > 0) {
            flatAsyncRoutes(item.children, item.meta.breadcrumb) // 递归遍历 children
        }
    }
    return routes
}


/**
 * 根据配置的路由数组，取里面的meta.permission，与role里面的permission比对，是否有权限访问
 * @param routerMap
 * @param role
 * role.permissionList = ['user','guest']
 * @returns {*}
 */
export function filterAsyncRouter(routerMap, role) {
    const accessedRouters = routerMap.filter(route => {
        if (hasPermission(role.permissionList, route)) {
            if (route.children && route.children.length) {
                route.children = filterAsyncRouter(route.children, role)
            }
            return true
        }
        return false
    })
    return accessedRouters
}

/**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permission
 * @param route
 * @returns {boolean}
 */
export function hasPermission (permission, route) {
    if (route.meta && route.meta.permission) {
        if (permission === undefined) {
            return false
        }
        let flag = false
        for (let i = 0, len = permission.length; i < len; i++) {
            flag = route.meta.permission.includes(permission[i])
            if (flag) {
                return true
            }
        }
        return false
    }
    return true
}

/**
 * 通过菜单名称过滤菜单
 * @param userMenus
 * @param allowMenus
 * @returns {*}
 */
export function filterMenusByMenuName(userMenus, allowMenus) {
    // 后面换成path
    const allowedIds = tool.array.getColumn(allowMenus, 'id')
    // 把404手动加上
    allowedIds.push('999999')
    // console.log('筛选出来的菜单', menus)
    return tool.array.filterTree(userMenus, allowedIds, 'id')
}
